package com.gw.quotes.adapter;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.gw.quotes.MyApplication;
import com.gw.quotes.R;
import com.gw.quotes.constant.Constant;
import com.gw.quotes.entity.business.OrderListEntity.OrderItem;
import com.gw.quotes.entity.business.OrderListEntity.OrderItem.OrderGoodsItem;
import com.gw.quotes.entity.system.User;
import com.gw.quotes.net.BaseServiceInter;
import com.gw.quotes.net.HttpCallBack;
import com.gw.quotes.net.Request;
import com.gw.quotes.net.Response;
import com.gw.quotes.net.service.OrderStatucChangeServiceImpl;
import com.gw.quotes.util.CommonTools;
import com.gw.quotes.util.DialogUtils;
import com.gw.quotes.util.DialogUtils.DialogCallBack;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.yxw.view.YXWProgressDialog;
import com.yxw.view.YXWProgressDialog.YXWDialog;
import com.yxw.view.util.ResFinder;

public class OrderAdapter extends BaseAdapter {

	private ArrayList<OrderItem> list;
	private Context context;
	private int resource;
	private DisplayImageOptions options;
	protected ImageLoader imageLoader;
	protected YXWDialog dialog;
	
	public OrderAdapter(Context context, int layoutId, ArrayList<OrderItem> list) {
		this.context = context;
		this.resource = layoutId;
		this.list = list;
		this.imageLoader = ImageLoader.getInstance();
		this.imageLoader.init(ImageLoaderConfiguration.createDefault(context));
		
		// 初始化dialog
		dialog = new YXWProgressDialog(context).createDialog("加载中…");
				
		this.options = new DisplayImageOptions.Builder()
				.showImageOnLoading(R.drawable.ic_empty)
				.showImageForEmptyUri(
						ResFinder.getR(context, "R.drawable.ic_empty"))
				.showImageOnFail(ResFinder.getR(context, "R.drawable.ic_empty"))
				.cacheInMemory(true).cacheOnDisk(true)
				.displayer(new FadeInBitmapDisplayer(500))// 是否图片加载好后渐入的动画时间
				.bitmapConfig(Bitmap.Config.RGB_565).build();
	}

	@Override
	public int getCount() {
		return this.list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final OrderItem order = list.get(position);
		List<OrderGoodsItem> orderGoodsItem = (List<OrderGoodsItem>) order
				.getOrderGoodsList();
		if (convertView == null) {
			convertView = LayoutInflater.from(this.context).inflate(
					this.resource, parent, false);
		}
		TextView no = (TextView) convertView.findViewById(R.id.order_no);
		TextView state = (TextView) convertView.findViewById(R.id.order_state);
		TextView goods_name = (TextView) convertView
				.findViewById(R.id.order_goods_name);
		TextView goods_price = (TextView) convertView
				.findViewById(R.id.order_goods_price);
		TextView price = (TextView) convertView.findViewById(R.id.order_price);
		TextView num = (TextView) convertView.findViewById(R.id.order_num);
		TextView btn = (TextView) convertView.findViewById(R.id.order_btn);
		TextView orderRefuse = (TextView) convertView.findViewById(R.id.order_refuse_btn);
		ImageView goods_img = (ImageView) convertView
				.findViewById(R.id.order_goods_img);
		if (2 == order.getStatus() || 3 == order.getStatus()) {
			
			btn.setText("交易详情");
			
			orderRefuse.setVisibility(View.GONE);// 隐藏-退回订单
			
			if (3 == order.getStatus()) {
				state.setText("退回订单");
			} else {
				state.setText("已确认");
			}
			btn.setTextColor(Color.BLACK);
			btn.setBackgroundResource(R.drawable.bg_corners_border);
			
			orderRefuse.setTextColor(Color.BLACK);
			orderRefuse.setBackgroundResource(R.drawable.bg_corners_border);
		} else {
			state.setText("待确认");
			orderRefuse.setVisibility(View.VISIBLE);// 显示-退回订单
			
			// 待确认-确认订单
			btn.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					// 二次确认
					DialogUtils.confirmDialog("是否确认订单?", context, new DialogCallBack() {
						@Override
						public void onPositiveButton(Object o) {
							OrderSubmit(order, Constant.ORDER_STATUS_2, "");
						}
						@Override
						public void onNegativeButton(Object o) {
							super.onNegativeButton(o);
						}
					});
				}
			});
			
			// 待确认-退回订单
			orderRefuse.setOnClickListener(new OnClickListener() {
				public void onClick(View v) {
					// 退回意见
					DialogUtils.inputTitleDialog("退回订单?", "退回意见:", context, new DialogCallBack() {
						
						@Override
						public void onPositiveButton(Object t) {
							String refuseMes = t.toString();
							OrderSubmit(order, Constant.ORDER_STATUS_4, refuseMes);
							
						}
						
						@Override
						public void onNegativeButton(Object o) {
							super.onNegativeButton(o);
						}
						
					});
				}
			});
			
			btn.setTextColor(Color.WHITE);
			btn.setBackgroundResource(R.drawable.orange_btn);
			orderRefuse.setTextColor(Color.WHITE);
			orderRefuse.setBackgroundResource(R.drawable.orange_btn);
		}
		state.setText("");
		no.setText(order.getCode());
		if (order.getOrderGoodsList() != null
				&& order.getOrderGoodsList().size() > 0
				&& order.getOrderGoodsList().get(0) != null) {
			goods_name.setText(order.getOrderGoodsList().get(0).getGoodsname());
		} else {
			goods_name.setText(order.getGoodsclassname());
		}

		goods_price.setText(String.format("￥%.2f",(order.getTotal() / order.getQty())));
		price.setText(String.format("￥%.2f",order.getTotal()));
		num.setText("共" + order.getQty() + "件商品");
		if (orderGoodsItem.size() > 0) {
			this.imageLoader.displayImage(orderGoodsItem.get(0).getImgurl(),
					goods_img, this.options);
		}
		return convertView;
	}
	
	/**
	 * 订单提交(确认/退回)
	 * @param order
	 * @param status
	 * @param remark
	 */
	public void OrderSubmit(final OrderItem order,final String status,String remark){
		dialog.show();
		 BaseServiceInter httpService = new OrderStatucChangeServiceImpl();
		Request request = new Request();
		User user = MyApplication.instance().getLoginUser();
		request.setLoginname(user.getLoginname());
		request.setTicket(user.getTicket());
		
		// 设置参数 
		String jsonconditions = "{'orderguid':'%s','status':'%s','remark':'%s'}";
		jsonconditions = String.format(jsonconditions, order.getOrderguid(), status, remark);
		request.setJsonconditions(jsonconditions);
		Response response = httpService.handler(request,
				new HttpCallBack<Response<User>>() {
					@Override
					public void onFinished(Response<User> response) {
						if (response.getResult() == Response.RESULT_SUCCESS) {
							Toast.makeText(context,response.getMsg(),Toast.LENGTH_SHORT).show();
							
							order.setStatus(Integer.parseInt(status));// 更新状态
							removeListItem(order);// list中删除item项
							OrderAdapter.this.notifyDataSetChanged();// 刷新当前页
							
						} else {
							CommonTools.showShortToast(context,response.getMsg());
						}
						dialog.dismiss();
					}
				});
	}
	
	/**
	 * list中删除item项
	 * @param item
	 */
	public void removeListItem(OrderItem item)
	{
		list.remove(item);
	}

}
